
import db from './mysqlHelper.js';
import { qipiao_get } from './qipiao.js';

/**
 *  支付通知处理方法
 * @param {*} billNo 
 * @param {*} pay_amount 
 * @param {*} discount_amount 
 * @returns 
 */
async function pay_notice_process(billNo, pay_amount, discount_amount = 0) {

    let sqls = [];
    sqls.push({ sql: `update order_info set pay_status=10 ,pay_time='${moment().format('YYYY-MM-DD HH:mm:ss')}' where pay_sn='${billNo}'` });
    let order = await db.findOne('order_info', { pay_sn: billNo });
    if (order instanceof Error) {
        console.error(`支付成功 但查询订单出错 ${order.message}  返回内容: ${JSON.stringify(billPayment)}`);
        return false;
    }


    if (order.category_name == 'movie') {
        //更新电影票对应的订单状态
        sqls.push({
            sql: `update movie_order set state=1 ,pay_time='${moment().format('YYYY-MM-DD HH:mm:ss')}',pay_sn='${order.pay_sn}',
            openid=? ,phone=? ,user_ticket_id=?,pay_amount=?,discount_amount=?  where id=?`, param: [order.openid, order.phone, order.user_ticket_id, pay_amount, discount_amount, order.order_id]
        });
    } else if (order.category_name == 'giftcard') {
        //更新卡券的订单状态
        sqls.push({
            sql: `update gift_card_order set state=1 ,pay_time='${moment().format('YYYY-MM-DD HH:mm:ss')}',pay_sn='${order.pay_sn}',
          openid=? ,phone=? ,user_ticket_id=?,pay_amount=?,discount_amount=?  where id=?`, param: [order.openid, order.phone, order.user_ticket_id, pay_amount, discount_amount, order.order_id]
        });

    } else if (order.category_name == 'food') {
        //更新餐饮订单状态
        sqls.push({
            sql: `update food_order set state=1 ,pay_time='${moment().format('YYYY-MM-DD HH:mm:ss')}',pay_sn='${order.pay_sn}',
          openid=? ,phone=? ,user_ticket_id=?,pay_amount=?,discount_amount=?  where id=?`, param: [order.openid, order.phone, order.user_ticket_id, pay_amount, discount_amount, order.order_id]
        });
    }
    //如果有优惠券 则更新优惠券的使用记录
    if (order.discount != null && order.discount != 0) {
        let user_ticket = await db.findOne('user_ticket', { id: order.user_ticket_id });
        if (user_ticket instanceof Error) {
            console.error(`支付回调中 用户券核销查询用户券失败  用户券ID: ${order.user_ticket_id}  错误原因: ${user_ticket.message}`);
            return false;
        }
        if (user_ticket == null) {
            console.error(`支付回调中 用户券核销查询用户券失败  用户券ID: ${order.user_ticket_id}  未查询到用户券`);
            return false;
        }
        let use_record = {
            user_ticket_id: order.user_ticket_id,
            isp_code: user_ticket.isp_code,
            isp_path: user_ticket.isp_path,
            packet_id: user_ticket.packet_id,
            type_id: user_ticket.type_id,
            use_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            phone: user_ticket.phone,
            openid: user_ticket.openid,
            balance: user_ticket.num,
            use_value: 1,
            inventory: user_ticket.num - 1,
        }
        sqls.push({ sql: 'insert into user_use_record set ?', param: [use_record] });
        //更新领券记录表中的数量
        sqls.push({ sql: `update user_ticket set num=num-1,use_num=use_num+1 where id=${order.user_ticket_id}` });
    }
    //如果有使用代金券 则更新代金券的使用记录
    if (order.voucher_amt > 0) {
        //查询订单对应用户下的代金券
        let sql = `select * from user_voucher  where (openid='${order.openid}' or phone='${order.phone}') and expire_time>'${moment().format('yyyy-MM-DD HH:mm:ss')}' and num>0`;
        let user_vouchers = await db.query(sql);
        if (user_vouchers instanceof Error) {
            console.error(`支付回调中 代金券核销查询代金券失败  错误原因: ${user_vouchers.message}`);
            return false;
        }
        if (user_vouchers == null || user_vouchers.length == 0) {
            console.error(`支付回调中 代金券核销查询代金券失败  未查询到代金券 openid='${order.openid}' or phone='${order.phone}'`);
            return false;
        }
        let index = 0;
        let isOver = false;
        while (order.voucher_amt > 0 && !isOver) {
            let user_voucher = user_vouchers[index];
            if (user_voucher.num >= order.voucher_amt) {
                //如果代金券数量大于订单金额 则直接更新代金券数量
                sqls.push({ sql: `update user_voucher set num=num-${order.voucher_amt},use_num=use_num+${order.voucher_amt} where id=${user_voucher.id}` });
                let voucher_use_record = {
                    user_voucher_id: user_voucher.id,
                    isp_code: user_voucher.isp_code,
                    isp_path: user_voucher.isp_path,
                    use_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                    phone: user_voucher.phone,
                    openid: user_voucher.openid,
                    balance: user_voucher.num,
                    use_value: order.voucher_amt * -1,
                    inventory: user_voucher.num - order.voucher_amt
                }
                sqls.push({ sql: 'insert into user_voucher_use_record set ?', param: [voucher_use_record] });
                isOver = true;

            } else {
                //如果代金券数量小于订单金额 则直接更新代金券数量
                sqls.push({ sql: `update user_voucher set num=0,use_num=use_num+${user_voucher.num} where id=${user_voucher.id}` });
                let voucher_use_record = {
                    user_voucher_id: user_voucher.id,
                    isp_code: user_voucher.isp_code,
                    isp_path: user_voucher.isp_path,
                    use_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                    phone: user_voucher.phone,
                    openid: user_voucher.openid,
                    balance: user_voucher.num,
                    use_value: user_voucher.num * -1,
                    inventory: 0
                }
                sqls.push({ sql: 'insert into user_voucher_use_record set ?', param: [voucher_use_record] });
                order.voucher_amt -= user_voucher.num;
            }
            index++;
        }
    }



    //开始执行事务
    let res = await db.transaction(sqls);
    if (res instanceof Error) {
        console.log(`支付成功 但更新订单状态失败  出错原因: ${res.message}  返回内容: ${JSON.stringify(billPayment)}`);
        return false;
    }

    if (order.category_name == 'movie') {
        //通知有票票支付成功
        res = await qipiao_get('/api/movie/pay_order', { id: order.order_id, test: false });
        console.log('通知有票票支付成功返回', res);
        if (res.err) {
            console.error(`支付成功 但通知有票票失败  电影订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res.err)}`);
            return false;
        }
        console.log(`支付成功 通知有票票成功  电影订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res)}`);
        return true;
    }
    else if (order.category_name == 'giftcard') {
        //通知有票票支付成功
        res = await qipiao_get('/api/gift_card/pay_order', { id: order.order_id, test: false });
        if (res.code != 0) {
            console.error(`支付成功 但通知有票票失败  卡券订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res)}`);
            return false;
        }
        console.log(`支付成功 通知有票票成功  卡券订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res)}`);
        return true
    }
    else if (order.category_name == 'food') {
        //通知有票票支付成功
        res = await qipiao_get('/api/kfc/pay_order', { id: order.order_id, test: false });
        if (res.code != 0) {
            console.error(`支付成功 但通知有票票失败  餐饮订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res)}`);
            return false;
        }
        console.log(`支付成功 通知有票票成功  餐饮订单ID: ${order.order_id}  有票返回: ${JSON.stringify(res)}`);
        return true;
    }
}

export  { pay_notice_process }
